﻿using System;
using System.Collections.ObjectModel;
using MvvmFoundation.Wpf;
using WpfApplication1.Wpf;

namespace WpfApplication1
{
    public abstract class CrudViewModel<T> : ViewModel
        where T:class
    {
        private  T _selectedItem;
        private ObservableCollection<T> _items;
        private RelayCommand _readCommand;
        private RelayCommand<T> _deleteCommand;
        private RelayCommand<T> _updateCommand;
        private readonly ICrudRepository<T> _context;

        protected CrudViewModel(ICrudRepository<T> context )
        {
            _context = context;
        }


        public T SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;
                RaisePropertyChanged("SelectedItem");
            }
        }

        public RelayCommand ReadCommand 
        {
            get
            {
                if (_readCommand == null)
                {
                    _readCommand = new RelayCommand(Read);
                }
                return _readCommand;
            } 
        }
        public RelayCommand<T> DeleteCommand 
        {
            get
            {
                if (_deleteCommand == null)
                {
                    _deleteCommand = new RelayCommand<T>(Delete,CanDelete);
                }
                return _deleteCommand;
            } 
        }
        public RelayCommand<T> UpdateCommand 
        {

            get
            {
                if (_updateCommand == null)
                {
                    _updateCommand = new RelayCommand<T>(Save, CanSave);
                }
                return _updateCommand;
            } 
        }

        public ObservableCollection<T> Items 
        {
            get
            {
                if (_items == null)
                {
                    _items = new ObservableCollection<T>();
                }
                return _items;
            }
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }
                _items = value;
            }
        }

        protected abstract void Read();
       
        protected bool CanDelete(T item)
        {
            return item != null;
        }

        protected void Delete(T item)
        {
            _context.Remove(item);
            _context.SaveChanges();
            Read();
        }

        protected void Save(T item)
        {
            _context.SaveChanges();
            Read();
        }

        protected bool CanSave(T item)
        {
            return _context.HasUnsavedChanges();
        }
       

    }

}
